package com.freeter.common.utils;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

public class ScriptEngineUtil {

    private static  ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    private  static ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");

    public static double evalDouble(String expression, Map<String,Object> params) throws ScriptException {

        Bindings bindings =  scriptEngine.createBindings();
        for(Map.Entry<String,Object> entry : params.entrySet()) {
            scriptEngine.put(entry.getKey(), entry.getValue());
        }
        return Double.valueOf(scriptEngine.eval(expression).toString());
    }
    public static Boolean evalBoolean(String expression, Map<String,Object> params) throws ScriptException {

        Bindings bindings =  scriptEngine.createBindings();
        for(Map.Entry<String,Object> entry : params.entrySet()) {
            scriptEngine.put(entry.getKey(), entry.getValue());
        }
        return (Boolean) scriptEngine.eval(expression);
    }
}
